package cn.com.basic.framework.web.error;

import cn.com.basic.framework.exception.enums.errors.SystemError;
import cn.com.basic.framework.web.domain.RespResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author jh
 * @date 2019/5/21 11:27
 * @Description: 全局异常处理
 */

@ControllerAdvice(annotations = RestController.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RespResult handleExp(Exception e) {
        logger.error("Unknown Exception: {}", e);
        e.printStackTrace();
        return RespResult.builder().code(SystemError.SYSTEM_EXECUTE_ERROR.getKey()).message(SystemError.SYSTEM_EXECUTE_ERROR.getValue() + ":" + e.getMessage()).build();
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public RespResult handleBizExp(BizException e) {
        logger.error("Biz Exception: {}", e.getMessage());
        e.printStackTrace();
        return RespResult.builder().code(e.getErrorCode()).message(e.getMessage()).build();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public RespResult handleMethodArgumentNotValidExp(MethodArgumentNotValidException e) {
        FieldError error = (FieldError) e.getBindingResult().getAllErrors().get(0);
        StringBuilder sb = new StringBuilder();
        String errorMsg = sb.append(error.getField()).append("(").append(error.getRejectedValue()).append(")")
                .append(" : ").append(error.getDefaultMessage()).toString();
        logger.error("MethodArgumentNotValid Exception: {}", errorMsg);
        e.printStackTrace();
        return RespResult.builder().code(SystemError.SYSTEM_EXECUTE_ERROR.getKey()).message(e.getMessage()).build();
    }
}
